import angular from "angular"
import serverName from "./rent_detail.server"
import "./tpl/addOne"
import { property, merge, flowRight, map } from "lodash"
import qs from "querystring"
import util from '@yunke/core/util';

const comfirm = msg => new Promise((resolve, reject) => util.confirm(msg, {
    ok: resolve, cancel: reject
}))
angular.module('rentDetail')
    .controller('rentDetailController', ['$scope', '$routeParams', serverName, "addOneModal", function ($scope, $routeParams, rentDetailServer, Modal) {
        const contractIdObj = { contractId: $routeParams.id }
        const generCpId = item => merge({ Id: item.Id }, contractIdObj)
        function updateList() {
            return rentDetailServer.getDetailList($routeParams.id)
                .then(property("data.data"))
                .then(data => {
                    const { AdList, amount } = data
                    $scope.AdList = map(AdList, (ad) => {
                        ad.startOn = ad.startOn !== '0' ? ad.startOn + '000' : null
                        ad.endOn = ad.endOn !== '0' ? ad.endOn + '000' : null
                        return ad
                    });
                    $scope.amount = amount
                })
        }
        function open(query) {
            let str = qs.stringify(query)
            str = str !== "" ? "&" + str : ""
            window.open(`/api/index.php?r=contract/download-pdf${str}`)
        }
        $scope.addNewOne = function () {
            Modal({ title: "新增", params: contractIdObj }).promise
                .then(data => rentDetailServer.addAdList(contractIdObj, data))
                .then(updateList);
        }
        $scope.edit = item => Modal({ item, title: "修改", params: generCpId(item) }).promise
            .then(data => rentDetailServer.editAdList(generCpId(item), data))
            .then(updateList)

        $scope.view = function (item) {
            open(merge(generCpId(item), { type: "view" }))
        }
        $scope.download = flowRight(open, generCpId)
        $scope.up = function (item, file) {
            rentDetailServer.editAdList(generCpId(item), { "file": file })
                .then(updateList)
        }
        $scope.delSelf = item => comfirm("确定删除")
            .then(() => rentDetailServer.delAdList(generCpId(item)))
            .then(updateList, console.log)
        $scope.delFile = item => comfirm("确定删除")
            .then(() => rentDetailServer.delAdPdf(generCpId(item)))
            .then(updateList, console.log)
        updateList();
    }]);